import json
from web3 import Web3
import asyncio

default_config = {
    "provider_url": "http://10.101.50.37:8545",
    "copyright_addr": "0x1752a721E5769f075C992d30857D77Bc8FE1Fa9d",
    "copyright_json": "/mnt/e/pydev/hash-store/build/contracts/DigitalRight.json",
}


def connect_contract(
    provider_url=default_config["provider_url"],
    contract_addr=default_config["copyright_addr"],
    contract_json=default_config["copyright_json"],
    use_account=0,
):
    # add your blockchain connection information
    web3 = Web3(Web3.HTTPProvider(provider_url))
    web3.eth.default_account = web3.eth.accounts[use_account]
    with open(contract_json) as json_file:
        contract_json = json.loads(json_file.read())
    contract = web3.eth.contract(address=contract_addr, abi=contract_json["abi"])
    tx_hash = contract.functions.initOracle(web3.eth.default_account).transact()
    # tx_receipt = web3.eth.wait_for_transaction_receipt(tx_hash)
    # print(tx_receipt)
    oracleParams = contract.functions.getOracle().call()
    return contract, oracleParams


# define function to handle events and print to the console
def handle_event(event):
    print(Web3.to_json(event))
    # and whatever


# asynchronous defined function to loop
# this loop sets up an event filter and is looking for new entires for the "Uploaded" event
# this loop runs on a poll interval
async def log_loop(event_filter, poll_interval):
    while True:
        for Uploaded in event_filter.get_new_entries():
            handle_event(Uploaded)
        await asyncio.sleep(poll_interval)


def oracle_serve(contract):
    event_filter = contract.events.Uploaded.create_filter(fromBlock="0x0")
    loop = asyncio.get_event_loop()
    try:
        loop.run_until_complete(asyncio.gather(log_loop(event_filter, 2)))
    finally:
        # close loop to free up system resources
        loop.close()


# oracle service start
# multiprocessing.Process(target=oracle_serve, args=(digital_copyright_contract,)).start()

# upload to blockchain
# web3.eth.default_account = web3.eth.accounts[0]
# tx_hash = digital_copyright_contract.functions.upload("A", "A").transact()
